package com.atguigu.juc_day02;

/**
 * java
 * 2022/9/9 00 25
 */

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @auther zzyy
 * @create 2022-06-17 11:39
 * 多线程之间按顺序调用，实现A->B->C
 * 三个线程启动，要求如下：
 *
 * AA打印5次，BB打印10次，CC打印15次
 * 接着
 * AA打印5次，BB打印10次，CC打印15次
 * ......来10轮
 *
 * 1 线程 操作  资源类
 *
 * 2 判断 干活 通知
 *
 * 3 防止虚假唤醒
 *
 * 4 多线程的标志位变更
 */
class ShareResource2{
    private int flag=1;
    private Lock lock = new ReentrantLock ();
    private Condition condition1 = lock.newCondition ();
    private Condition condition2 = lock.newCondition ();
    private Condition condition3 = lock.newCondition ();

    public void print5() throws InterruptedException {
        lock.lock ();
        while (flag != 1) {
            condition1.await ();
        }
        for (int i = 0; i < 5; i++) {
            System.out.println (Thread.currentThread ().getName () + (i + 1));
        }
        flag = 2;
        condition2.signal ();
        lock.unlock ();
    }
        public void print10() throws InterruptedException {
            lock.lock ();
            while (flag!=2){
                condition2.await ();
            }
            for (int i = 0; i < 10; i++) {
                System.out.println (Thread.currentThread ().getName ()+(i+1));
            }
            flag=3;
            condition3.signal ();
            lock.unlock ();
        }
        public void print15() throws InterruptedException {
            lock.lock ();
            while (flag!=3){
                condition3.await ();
            }
            for (int i = 0; i < 15; i++) {
                System.out.println (Thread.currentThread ().getName ()+(i+1));
            }
            flag=1;
            condition1.signal ();
            lock.unlock ();
        }}
public class ThreadOrderAccess2 {
    public static void main (String[] args) {
        ShareResource2 shareResource2 = new ShareResource2 ();
        new Thread (()->{
            for (int i = 0; i < 10; i++) {
                try {
                    shareResource2.print5 ();
                } catch (InterruptedException e) {
                    throw new RuntimeException (e);
                }
            }
        },"A").start ();
        new Thread (()->{
            for (int i = 0; i < 10; i++) {
                try {
                    shareResource2.print10 ();
                } catch (InterruptedException e) {
                    throw new RuntimeException (e);
                }
            }
        },"B").start ();
        new Thread (()->{
            for (int i = 0; i < 10; i++) {
                try {
                    shareResource2.print15 ();
                } catch (InterruptedException e) {
                    throw new RuntimeException (e);
                }
            }
        },"C").start ();
    }
}
